from yt_download import get_mp3_from_ut, get_info_yt_video
from mp3tag import modified_id3
from feed import CheckFeed
from agent import send_audio
import sys
import time
import validators
import os
import logging

yt_feed = CheckFeed()
videos = yt_feed.read()
logging.basicConfig(
                    format='%(asctime)s %(message)s',
                    datefmt='%Y-%m-%d %H:%M:%S',
                    level=logging.INFO)

num_of_items = 5


def print_video_list():
    print("The list of titles of new items in youtube channel:")
    if videos:
        for i in range(0, num_of_items):
            print(f"=== {i + 1}. {videos[i]['title']}")
    else:
        print("ERROR: Can't get any videos")

print_video_list()

while True:
    select = input("Insert num of video to convert or type command exit/link/list: ")
    if select == "exit":
        logging.info("Terminate the script")
        sys.exit()
    elif select == "list":
        print("\n==============================\n")
        print_video_list()
    elif select == "link":
        while True:
            link = input("Insert the valid link to youtube video: ")
            if validators.url(link):
                break
        video = get_info_yt_video(link)
        print(f"Video title is: {video['title']}")
        break
    else:
        try:
            video_index = int(select) - 1
            if 0 <= video_index < num_of_items:
                video = videos[video_index]
                break
            else:
                logging.warning(f"Number is not from range (1, {num_of_items}). Try again")
        except ValueError:
            logging.warning("ERROR! It's not integer. Try again")

while True:
    answer = input("Type the tags for mp3 file. Format: artist|title ")
    tags = answer.split("|")
    if len(tags) == 2:
        print(f"----Artist: {tags[0]}\n----Title: {tags[1]}")
        if input("Is it right? y/n: ").lower() != "n":
            break
    else:
        logging.warning("This is not right string")

while True:
    if get_info_yt_video(video['link'])['is_live']:
        logging.warning('This stream is on. Waiting for end')
        time.sleep(30 * 60)
    else:
        break


logging.info("Start Downloading")
mp3 = get_mp3_from_ut(video)
if mp3:
    files = [f for f in os.listdir() if f.endswith(".mp3") and f.startswith(mp3["title"][:9])]
    if len(files) == 1:
        file_name = files[0]
    else:
        raise RuntimeError("Something bad happened")

    print(f"Video title is: {mp3['title']}")


    modified_id3(file_name, tags[0], tags[1])
    logging.info(f"----DONE!\n----File name: {file_name}")
    send_audio(file_name, tags[0], tags[1])
    logging.info("Uploading completed")
    if os.path.isfile(file_name):
        os.remove(file_name)
        logging.info(f"file {file_name} was removed")
    else:
        logging.warning("File doesn't exists! Remove all mp3 files in folder")
        dir_name = os.getcwd()
        files = os.listdir(dir_name)
        for file in files:
            if file.endswith(".mp3"):
                os.remove(os.path.join(dir_name, file))


